package future;

import future.service.PoiService;
import future.service.ProductService;
import future.service.model.Model;
import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author kxd
 * @datetime 2022/3/22 9:48
 */
public class CompletableFutureExamp {
    @Test
    public void test() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello")
                .thenCombine(CompletableFuture.supplyAsync(() -> "world"), (s1, s2) -> s1 + s2);
        String res = future.get();
        System.out.println(res);
        String poiId = "test";
        Model model = new Model();
        PoiService poiService = new PoiService();
        ProductService productService = new ProductService();
        CompletableFuture<Void> poilDTOFuture = CompletableFuture
                .supplyAsync(() -> poiService.loadPoi(poiId))
                .thenAccept(poi -> {
                    model.setTitle(poi.getModel());
                });
        CompletableFuture<Void> productFuture = CompletableFuture
                .supplyAsync(() -> productService.findList(poiId))
                .thenAccept(list -> {
                    model.setCount(list.size());
                    model.setDesc("more");
                });
        CompletableFuture.allOf(poilDTOFuture, productFuture).join();
    }

    @Test
    public void test01() {
        Integer age = -1;
        CompletableFuture<Void> maturityFuture = CompletableFuture.supplyAsync(() -> {
            if (age < 0) {
                throw new IllegalArgumentException("age not be negative");
            }
            if (age > 18) {
                return "Audit";
            } else {
                return "Child";
            }
        }).exceptionally(ex -> {
            System.out.println("have an exception");
            return "unknown";
        }).thenAccept(s -> System.out.println(s));
    }
}
